package org.dawfinn.droiditarian;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dawfinn.droiditarian.proto.Droiditarian;
import org.dawfinn.droiditarian.proto.Droiditarian.DeedLocation.Builder;
import org.dawfinn.droiditarian.server.Geohash;
import org.dawfinn.droiditarian.server.data.DeedLocation;

import com.google.protobuf.ByteString;

@SuppressWarnings("serial")
public class DeedLocationListServlet extends HttpServlet {
	private static final int RESULT_COUNT = 15;

	private static final String MIN_LAT_PARAM = "minLat";
	private static final String MIN_LNG_PARAM = "minLng";
	private static final String MAX_LAT_PARAM = "maxLat";
	private static final String MAX_LNG_PARAM = "maxLng";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");

		OutputStream out = resp.getOutputStream();

		Float minLat = getFloatParam(req, MIN_LAT_PARAM);
		Float minLng = getFloatParam(req, MIN_LNG_PARAM);
		Float maxLat = getFloatParam(req, MAX_LAT_PARAM);
		Float maxLng = getFloatParam(req, MAX_LNG_PARAM);

		List<DeedLocation> deedLocs;

		if (minLat == null || minLng == null || maxLat == null
				|| maxLng == null)
			deedLocs = DeedLocationQuery.getDeedLocations(RESULT_COUNT);
		else
			deedLocs = DeedLocationQuery.getDeedLocations(RESULT_COUNT, minLat,
					minLng, maxLat, maxLng);

		for (DeedLocation loc : deedLocs) {
			double[] latlng = Geohash.getInstance().decode(loc.getGeohash());
			float lat = (float) latlng[Geohash.LAT];
			float lng = (float) latlng[Geohash.LNG];

			Builder builder = Droiditarian.DeedLocation.newBuilder()
					.setLat(lat).setLng(lng).setDeedTitle(loc.getDeedTitle())
					.setKey(loc.getWebsafeKey());

			if (loc.getImage() != null)
				builder.setPicture(ByteString.copyFrom(loc.getImage()
						.getBytes()));

			builder.setLocality(loc.getLocality());
			builder.setCountry(loc.getCountry());

			builder.build().writeDelimitedTo(out);
		}

		out.close();
	}

	private static Float getFloatParam(HttpServletRequest req, String param) {
		try {
			return Float.valueOf(req.getParameter(param));
		} catch (Exception e) {
			return null;
		}
	}
}
